﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace Fadd.Messaging
{
	public class SubscriberCollection : IEnumerable<SubscriberWrapper>
	{
		private readonly Type _messageType;
		private readonly List<SubscriberWrapper> _items = new List<SubscriberWrapper>();

		public SubscriberCollection(Type messageType)
		{
			_messageType = messageType;
			//Type type = typeof (IMessageConsumer<>).MakeGenericType(messageType);
		}

		public void Add(object subscriber)
		{
			_items.Add(new SubscriberWrapper(_messageType, subscriber));
		}

		public void Remove(object subscriber)
		{
			var itemToRemove = _items.FindAll(wrapper => wrapper.Instance == subscriber);
			foreach (var value in itemToRemove)
				_items.Remove(value);
		}

		/// <summary>
		/// Returns an enumerator that iterates through the collection.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
		/// </returns>
		/// <filterpriority>1</filterpriority>
		public IEnumerator<SubscriberWrapper> GetEnumerator()
		{
			return _items.GetEnumerator();
		}

		/// <summary>
		/// Returns an enumerator that iterates through a collection.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
		/// </returns>
		/// <filterpriority>2</filterpriority>
		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
}